package org.jet.emall.rbac.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jet.emall.common.constant.UserStatus;
import org.jet.emall.common.util.ObjectUtils;
import org.jet.emall.log.AdminOperationLog;
import org.jet.emall.log.LogType;
import org.jet.emall.rbac.annotation.ApiInformation;

import org.jet.emall.common.restful.result.CommonPage;
import org.jet.emall.common.restful.result.CommonResult;
import org.jet.emall.rbac.dto.AdminUserViewDTO;
import org.jet.emall.rbac.dto.NewAdminUserDTO;
import org.jet.emall.rbac.dto.UpdateAdminUserDTO;
import org.jet.emall.rbac.model.NewAdminUserModel;
import org.jet.emall.rbac.model.UpdateAdminUserModel;
import org.jet.emall.rbac.service.CustomAdminUserService;
import org.jet.emall.rbac.transfer.AdminUserVoTransfer;
import org.jet.emall.rbac.vo.AdminUserViewVO;
import org.jet.emall.rbac.wrapper.UserIdAndRoleIdWrapper;
import org.jet.emall.rbac.wrapper.UserIdListAndStatusValueWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-05 14:44
 */

@Api(value = "管理员用户控制器")
@RestController
public class AdminUserController {

    Logger logger = LoggerFactory.getLogger(AdminUserController.class);
    @Autowired
    private CustomAdminUserService customAdminUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiInformation(function = "分页查找用户",menu = "用户管理")
    @ApiOperation(value="分页查询用户")
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public CommonResult<CommonPage<AdminUserViewVO>> page(@RequestParam String query, @RequestParam Integer pageNum, @RequestParam Integer pageSize){
        CommonPage<AdminUserViewDTO> page = customAdminUserService.page(query, pageNum, pageSize);
        //大家思考一下为什么要先将page转成Object,再转成其它类型
        ((CommonPage<AdminUserViewVO>)(Object)page).setList(AdminUserVoTransfer.INSTANCE.toVoList(page.getList()));
        return CommonResult.success((CommonPage<AdminUserViewVO>)(Object)page);
    }

    @ApiInformation(function = "ID查找用户")
    @ApiOperation(value = "ID查找用户")
    @RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
    public CommonResult<AdminUserViewVO> findById(@PathVariable Integer id){
        AdminUserViewDTO adminUserViewDTO = customAdminUserService.findById(id);
        AdminUserViewVO adminUserViewVO = AdminUserVoTransfer.INSTANCE.toVo(adminUserViewDTO);
        return CommonResult.success(adminUserViewVO,"ID查询用户成功");
    }

    @AdminOperationLog(value = "添加用户",logType = LogType.ADD)
    @ApiOperation(value = "添加用户")
    @ApiInformation(function = "添加用户",menu = "用户管理")
    @RequestMapping(value = "/users",method = RequestMethod.POST)
    public CommonResult<Object> add(@RequestBody NewAdminUserModel newUser){
        if(logger.isDebugEnabled()){
            logger.debug(newUser.toString());
        }
        if(ObjectUtils.isAnyNullFields(newUser)){
            return CommonResult.badRequest("新添用户的属性不能为空");
        }
        NewAdminUserDTO adminUserViewDTO = AdminUserVoTransfer.INSTANCE.toDto(newUser);
        //将密码加密
        adminUserViewDTO.setPassword(passwordEncoder.encode(adminUserViewDTO.getPassword()));
        customAdminUserService.save(adminUserViewDTO);
        return CommonResult.created("添加用户成功");
    }

    @AdminOperationLog(value = "删除用户",logType = LogType.DELETE)
    @ApiOperation(value="删除用户")
    @ApiInformation(function = "删除用户",menu = "用户管理")
    @RequestMapping(value = "/users",method = RequestMethod.DELETE)
    public CommonResult<Object> delete(@RequestBody List<Integer> ids){
        if(ids.isEmpty()){
            return CommonResult.badRequest("没有指定删除用户的ID");
        }
        customAdminUserService.delete(ids);
        return CommonResult.deleted("删除用户成功");
    }

    @AdminOperationLog(value = "修改用户",logType = LogType.UPDATE)
    @ApiOperation(value="修改用户")
    @ApiInformation(function = "修改用户",menu = "用户管理")
    @RequestMapping(value = "/users",method = RequestMethod.PUT)
    public CommonResult<Object> update(@RequestBody UpdateAdminUserModel updateUser){

        UpdateAdminUserDTO updateAdminUserDTO = AdminUserVoTransfer.INSTANCE.toDto(updateUser);
        updateAdminUserDTO.setPassword(passwordEncoder.encode(updateAdminUserDTO.getPassword()));
        customAdminUserService.update(updateAdminUserDTO);
        return CommonResult.success("修改用户成功");
    }

    @AdminOperationLog(value = "禁用/启用用户",logType = LogType.UPDATE)
    @ApiOperation(value="禁用/启用用户")
    @ApiInformation( function = "禁用/启用用户",menu = "用户管理")
    @RequestMapping(value = "/users",method = RequestMethod.PATCH)
    public CommonResult<Object> toggleUserStatus(@RequestBody UserIdListAndStatusValueWrapper wrapper){
        if(ObjectUtils.isAnyNullFields(wrapper) || wrapper.getIds().isEmpty()){
            return CommonResult.badRequest("用户禁用或启用操作失败,缺少参数");
        }
        List<Integer> ids = wrapper.getIds();
        Byte status = wrapper.getStatus();
        if(UserStatus.ENABLE.equals(status)){
            customAdminUserService.toggleUserStatus(ids,UserStatus.ENABLE);
            return CommonResult.success("用户启用成功");
        }else if(UserStatus.DISABLE.equals(status)){
            customAdminUserService.toggleUserStatus(ids, UserStatus.DISABLE);
            return CommonResult.success("用户禁用成功");
        }else{
            return CommonResult.badRequest("状态值异常，只能是"+UserStatus.ENABLE+"或"+UserStatus.DISABLE);
        }
    }

    @AdminOperationLog(value = "分配角色",logType = LogType.UPDATE)
    @ApiInformation(function = "分配角色",menu = "用户管理")
    @ApiOperation(value="分配角色")
    @RequestMapping(value = "/users/role",method = RequestMethod.PATCH)
    public CommonResult<Object> assignRole(@RequestBody UserIdAndRoleIdWrapper wrapper){
        Integer userId = wrapper.getUserId();
        Integer roleId = wrapper.getRoleId();
        customAdminUserService.assignRole(userId,roleId);
        return CommonResult.success("分配角色成功");
    }

}
